﻿@inject IAssistantService _assistantService
@inject IDialogService _dialogService
@inject ChatState _chatState

@implements IDisposable

<MudListItem Value="@Assistant!.Id" OnClick="SetSelectedAssistant">
    <ChildContent>
        <div class="d-flex flex-row flex-grow-1 gap-4">

            @if (@Assistant!.IsDefault)
            {
                <AvatarWithBadge AvatarImage="@Assistant?.AvatarUrl" BadgeIcon="@Icons.Material.Filled.Star" BadgeIconColor="gold" BadgeBackgroundColor="var(--mud-palette-dark)" />
            }
            else
            {
                <MudAvatar Size="@Size.Large" Class="my-auto">
                    <MudImage Src="@Assistant?.AvatarUrl" />
                </MudAvatar>
            }

            <div>
                <MudText Typo="Typo.h6">@Assistant?.Name</MudText>
                <MudText Typo="Typo.subtitle2">@Assistant?.Description</MudText>
            </div>
            <MudSpacer />
            <MudMenu Icon="@Icons.Material.Filled.MoreVert">
                <MudMenuItem OnClick="SetDefaultAssitant">Set as default</MudMenuItem>
                <MudMenuItem OnClick="() => EditAssistant(Assistant!.Id)">Edit</MudMenuItem>
                <MudMenuItem OnClick="ConfirmDeleteAssistantDialog">Delete</MudMenuItem>
            </MudMenu>
        </div>
    </ChildContent>
</MudListItem>
<MudDivider />

@code
{
    [Parameter] public AssistantResponse? Assistant { get; set; }
    [Parameter] public EventCallback<Guid> OnEdit { get; set; }
    [Parameter] public EventCallback OnDelete { get; set; }

    protected override void OnInitialized()
    {
        _chatState.SelectedAssistantChanged += StateHasChanged;
    }

    private async Task SetDefaultAssitant()
    {
        await Task.CompletedTask;
    }

    private async Task EditAssistant(Guid id)
    {
        await OnEdit.InvokeAsync(id);
    }

    private void SetSelectedAssistant()
    {
        _chatState.SetSelectedAssistant(Assistant!);
    }

    private async Task ConfirmDeleteAssistantDialog()
    {

        var parameters = new DialogParameters
        {
            { "Message", $"Confirm deletion of assistant '{Assistant?.Name}'?" },
            { "DetailMessage", "This action cannot be undone." }
        };

        var options = new DialogOptions { CloseOnEscapeKey = true };
        var dialog = _dialogService.Show<ConfirmDialog>("Delete Assitant", parameters, options);

        var result = await dialog.Result;

        if (!result.Canceled)
        {
            await _assistantService.DeleteAssistant(Assistant!.Id);
            await OnDelete.InvokeAsync();
        }
    }

    public void Dispose()
    {
        _chatState.SelectedAssistantChanged -= StateHasChanged;
    }
}
